import torch
import torch.nn as nn
from ghost_module import GhostModule

class GhostBottleneck(nn.Module):
    def __init__(self, in_channels, out_channels, stride=1, expansion=2):
        super(GhostBottleneck, self).__init__()
        hidden_channels = in_channels * expansion

        self.ghost1 = GhostModule(in_channels, hidden_channels, kernel_size=1, stride=1, relu=True)

        self.dwconv = nn.Sequential(
            nn.Conv2d(hidden_channels, hidden_channels, kernel_size=3, stride=stride,
                      padding=1, groups=hidden_channels, bias=False),
            nn.BatchNorm2d(hidden_channels),
            nn.ReLU(inplace=True)
        )

        self.ghost2 = GhostModule(hidden_channels, out_channels, kernel_size=1, stride=1, relu=False)

        self.downsample = None
        if stride != 1 or in_channels != out_channels:
            self.downsample = nn.Sequential(
                nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, bias=False),
                nn.BatchNorm2d(out_channels)
            )

        self.relu = nn.ReLU(inplace=True)

    def forward(self, x):
        identity = x

        out = self.ghost1(x)
        out = self.dwconv(out)
        out = self.ghost2(out)

        if self.downsample is not None:
            identity = self.downsample(x)

        out += identity
        return self.relu(out)

class GhostOnlyResNet(nn.Module):
    def __init__(self, num_classes=100):
        super(GhostOnlyResNet, self).__init__()
        self.stem = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False),
            nn.BatchNorm2d(64),
            nn.ReLU(inplace=True)
        )
        self.layer1 = self._make_layer(64, 64, num_blocks=2)
        self.layer2 = self._make_layer(64, 128, num_blocks=2, stride=2)
        self.layer3 = self._make_layer(128, 256, num_blocks=2, stride=2)
        self.layer4 = self._make_layer(256, 512, num_blocks=2, stride=2)
        self.pool = nn.AdaptiveAvgPool2d(1)
        self.fc = nn.Linear(512, num_classes)

    def _make_layer(self, in_channels, out_channels, num_blocks, stride=1):
        layers = [GhostBottleneck(in_channels, out_channels, stride)]
        for _ in range(1, num_blocks):
            layers.append(GhostBottleneck(out_channels, out_channels))
        return nn.Sequential(*layers)

    def forward(self, x):
        x = self.stem(x)
        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)
        x = self.pool(x).flatten(1)
        return self.fc(x)
